//
//  ViewController.m
//  Lock
//
//  Created by Justsoso on 16/3/23.
//  Copyright © 2016年 Justsoso. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,assign) int tickets;
@property (nonatomic,strong) NSLock *lock;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.lock = [[NSLock alloc] init];
    
    self.tickets = 100;
    
    NSThread *sellerThread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket2) object:nil];
    sellerThread1.name = @"售票员(张三)";
    NSThread *sellerThread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket2) object:nil];
    sellerThread2.name = @"售票员(李四)";
    NSThread *sellerThread3 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket2) object:nil];
    sellerThread3.name = @"售票员(王五)";
    
    [sellerThread1 start];
    [sellerThread2 start];
    [sellerThread3 start];
}

- (void)sellTicket
{
    while (1)
    {
        NSLog(@"%@: 准备卖票",[NSThread currentThread].name);
        @synchronized(self)
        {
            int count = self.tickets;
            if (count > 0)
            {
                [NSThread sleepForTimeInterval:0.01];
                self.tickets = self.tickets - 1;
                NSLog(@"%@:卖出了一张票，剩余%i",[NSThread currentThread].name,self.tickets);
            }
            else
            {
                NSLog(@"卖光了");
                [NSThread exit];
            }
        }
    }
}

- (void)sellTicket2
{
    while (1)
    {
        if ([self.lock tryLock])
        {
            // 说明没有人加锁，那我就锁住
            // 开始卖票
            int count = self.tickets;
            if (count > 0)
            {
                [NSThread sleepForTimeInterval:0.03];
                self.tickets = self.tickets - 1;
                [self.lock unlock];
                NSLog(@"%@:卖出了一张票,剩余:%i",[NSThread currentThread].name,self.tickets);
                NSLog(@"%@:喝口水休息下!",[NSThread currentThread].name);
                [NSThread sleepForTimeInterval:0.01];
            }
            else
            {
                NSLog(@"%@:票卖光了",[NSThread currentThread].name);
                [self.lock unlock];
                [NSThread exit];
            }
        }
        else
        {
            NSLog(@"%@:有人正在卖票,那我看会报纸,等一会",[NSThread currentThread].name);
            [NSThread sleepForTimeInterval:0.01];
        }
    }
}


@end
